<?php

App::import('View','Giga');

class GigaModularView extends GigaView 
{
	//var $validBlocks = array('sidebar', 'header','debugInfo','footer','adminDashboard');
	var $blockContent = array();
	
	function __construct(&$controller, $register = true) {
		
		parent::__construct($controller, $register);
	}
	

	function render($action = null, $layout = null, $file = null)
	{
		callHooks('InitBlocks', null, $this);
		
		if (Configure :: read('cmsConfig.Module.moduleManager') == 1) {
			$this->helpers[] = "Modules.ModuleEditor";
		}
				
		cmsDebug('Rendering main view..');
		$out = parent::render($action, $layout, $file);
		cmsDebug('parsing inline modules');
		
		$out = $this->_parseModules($out);
		cmsDebug('parsing inline modules done');
		
		if($layout!='ajax')
		{
			cmsDebug('Parsing blocks now');
			$out = $this->_parseTags($out);
			cmsDebug('Blocks parsing ended');
		}
		cmsDebug('Rendered main view!');
		return $out;
	}

	
	function _parseModuleTag($matches)
	{
		preg_match_all('/([a-zA-Z0-9_-]+)[ \t]*=[ \t]*["]([^"]+)["]/', $matches[1], $out);
		$tagAttrs = array_combine($out[1], $out[2]);
		$moduleName = $tagAttrs['name'];
		unset($tagAttrs['name']);
		
		return $this->module($moduleName, $tagAttrs);		
	}
	function _parseModules($content)
	{
		if(!strpos($content, '<module'))
			return $content;
		$content = str_replace('</module>','', $content);
		$content = preg_replace_callback('|<module([^<>]+)>|', array($this, '_parseModuleTag'), $content);
    	return $content;
	}
	
	// remove this function when time is right
	function module($module, $attrs)
	{
		// hacked version of module class
		$module['params'] = $attrs;
		
		require_once(APP.'plugins'.DS.'modules'.DS.'vendors'.DS.'module.php');
		$moduleObj = new GigaModule($module);
		if($moduleObj)
		{
			return $moduleObj->getContent();
		}
		elseif(Configure::read()) {
			trigger_error("Unable to parse module");
			debug($module);
		}
		return '';
	}
	
	
	function _parseTags($content)
	{
		$this->validBlocks = Configure::read('availableBlocks');
		foreach($this->validBlocks as $block)
		{
			if(strpos($content, '<cms:'.$block.'>'))
			{
				//echo $this->getBlockContent($block); 
				$content = str_replace('<cms:'.$block.'>', $this->getBlockContent($block), $content);
				$replace = array('<cms:'.$block.'>', '</cms:'.$block.'>');
				
				$content = str_replace($replace, '', $content);
			}
		}
		return $content;
	}
	

	/**
	 * Gets block content using blocks/modules classes.
	 *
	 * @param unknown_type $blockName
	 * @return unknown
	 */
	function getBlockContent($blockName)
	{
		require_once(APP.'plugins'.DS.'modules'.DS.'vendors'.DS.'block.php');
		$blockObj = new Block($blockName, $this);
		//prd($blockObj);
		if($blockObj)
		{
			return $blockObj->getContent();
		}
		return 'null';
	}

	/**
	 * Sets blocks array for view variables
	 *
	 * @param unknown_type $content_for_layout
	 * @param unknown_type $layout
	 * @return unknown
	 */
	function renderLayout($content_for_layout, $layout = null)
	{
		if($layout!='ajax')
		{
			$this->viewVars['blocks'] = $this->blockContent;
		}

		$out = parent::renderLayout($content_for_layout, $layout);
		return $out;
	}

	/**
	 * Stores information for rendering of modules.
	 * This function expects order of all elements is set right, and no order key is missing.
	 *
	 * @param unknown_type $module
	 */
	function setBlockContent($module)
	{
		//ksort($this->blockContent);
		extract($module);	
		
		// append new module here - check if module place already taken
		if(isset($this->blockContent[$position][$order]))
		{
			ksort($this->blockContent[$position]);
			$i = count($this->blockContent[$position]);
			// shift all positions from $order by 1
			while($i>=$order)
			{
				$this->blockContent[$position][$i+1] =  $this->blockContent[$position][$i];
				$i--;
			}
		}
		if(isset($plugin))
			$this->blockContent[$position][$order]['name'] = $plugin."_".$name;
		else
			$this->blockContent[$position][$order]['name'] = $name;
		if(isset($params))
			$this->blockContent[$position][$order]['params'] = $params;
			
		$this->blockContent[$position][$order]['cache'] = $cache;
		$this->blockContent[$position][$order]['id'] = $id;
		$this->blockContent[$position][$order]['title'] = $title;
		if(isset($style))
			$this->blockContent[$position][$order]['style'] = $style;
		if(isset($showOnUrl))
			$this->blockContent[$position][$order]['showOnUrl'] = $showOnUrl;
		if(isset($exceptions))
			$this->blockContent[$position][$order]['exceptions'] = $exceptions;						
	}
	
	function appendModule($module, $position, $order)
	{
		$module['order'] = $order;
		$module['position'] = $position;		
		$this->setBlockContent($module);
	}
	
	function _buildModule($name, $params = array())
	{
		$module = array();
		$module['name'] = $name;
		if(isset($params['params']))
			$module['params'] = serialize($params['params']);
		$module['id'] = $params['id'];
		$module['heading'] = $params['heading'];
		if(isset($params['plugin']))
			$module['plugin'] = $params['plugin'];
		if(!isset($module['cache']))
			$params['cache'] = 0;
		$module['cache'] = $params['cache'];	
		
		return $module;	
	}
	

	
	function _addModuleEditor()
	{
		$this->addScript('moduleEditor', '<link rel="stylesheet" type="text/css" href="'.Helper::url('/modules/css/module.css').'" />');
		parent::addJUI();
		$this->addScript('moduleEditorJs','<script src="' . Helper::url('/modules/js/editor.js') . '"></script>');
	}

}
?>